package com.yike.base.tool;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import java.nio.file.Paths;
import java.util.UUID;

/**
 * @author Sakura
 * @date 2024/11/5 16:40
 */
public class VoiceReading {

    public static void main(String[] args) {
        String text = "你好呀，这是一段测试语音！";
        textToSpeechIO(text);
    }

    /**
     * 字符串文本转 wav格式 语音文件
     *
     * @param text 要读的文字字符串
     */
    public static void textToSpeechIO(String text) {
        String path = "D:\\Java\\test";
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String wavFilePath = Paths.get(path, uuid + ".wav").toString();

        ActiveXComponent axSpFileStream = null;
        ActiveXComponent axSpAudioFormat = null;
        ActiveXComponent axSpVoice = null;

        try {
            axSpFileStream = new ActiveXComponent("Sapi.SpFileStream");
            axSpAudioFormat = new ActiveXComponent("Sapi.SpAudioFormat");
            axSpVoice = new ActiveXComponent("Sapi.SpVoice");

            // 设置音频格式
            Dispatch.put(axSpAudioFormat, "Type", new Variant(22));  // 22 表示8kHz, 16位, 单声道
            Dispatch.putRef(axSpFileStream, "Format", axSpAudioFormat);

            // 打开文件流
            Dispatch.call(axSpFileStream, "Open", new Variant(wavFilePath), new Variant(3), new Variant(true));

            // 设置声音输出到文件
            Dispatch.putRef(axSpVoice, "AudioOutputStream", axSpFileStream);
            Dispatch.put(axSpVoice, "Volume", new Variant(100));  // 音量
            Dispatch.put(axSpVoice, "Rate", new Variant(1));      // 语速

            // 朗读并生成音频
            Dispatch.call(axSpVoice, "Speak", new Variant(text));

            System.out.println("输出语音文件成功，保存路径: " + wavFilePath);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            if (axSpFileStream != null) {
                Dispatch.call(axSpFileStream, "Close");
                axSpFileStream.safeRelease();
            }
            if (axSpAudioFormat != null) axSpAudioFormat.safeRelease();
            if (axSpVoice != null) axSpVoice.safeRelease();
        }
    }
}
